package com.test.testcrash;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.iflytek.crashcollect.CrashCollector;

/**
 * @author ruiding
 * @date 2016/4/22
 */
public class MyService extends Service {
    private final String TAG = "crashcollect_MyService";

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");
        if (intent != null) {
            String cmd = intent.getStringExtra("crash");
            if (!TextUtils.isEmpty(cmd)) {
                makeProcess1Crash();
            }
            String uid = intent.getStringExtra("setuid");
            if (!TextUtils.isEmpty(uid)) {
                setUid(uid);
            }
            String method = intent.getStringExtra("method");
            if ("makeanr".equals(method)) {
                makeAnr();
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void makeProcess1Crash() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(1000);
                String str = "hello";
                str.charAt(10);
            }
        }).start();
    }

    private void setUid(String uid) {
        Log.d(TAG, "setUid | uid = " + uid);
        CrashCollector.setUid(uid);
    }

    private void makeAnr() {
        Log.d(TAG, "makeAnr");
        for (int i = 0; i < 100; ++i) {
            try {
                Thread.sleep(1000 * 5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
